﻿@using Maestro.MapPublisher.Common
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@Model.Title</title>
    <link rel="stylesheet" href="assets/css/fontello.css" />
    <link rel="stylesheet" href="assets/leaflet.css" />
    <link rel="stylesheet" href="assets/easy-button.css" />
    <style type="text/css">
        html,
        body {
            padding: 0;
            margin: 0;
            overflow: hidden;
        }

        html,
        body,
        #map {
            width: 100%;
            height: 100%;
        }
        @if (!string.IsNullOrEmpty(Model.UTFGridUrl))
        {<text>
        #feature-info {
            font-family: Verdana, sans-serif;
            border-radius: 3px;
            padding: 4px;
            font-size: 0.8em;
            background-color: white;
            will-change: left,right,top,bottom;
            z-index: 500;
            user-select: text;
        }
        </text>
        }

        button.enable-tile-tooltips-active {
            background-color: #ff9900;
        }
    </style>
</head>

<body>
    <div id="map">

    </div>
    @if (!string.IsNullOrEmpty(Model.UTFGridUrl))
    {
        <div id="feature-info" style="display: none; position: absolute">
            <!-- Overlay with the feature info -->
            <div id="feature-name">&nbsp;</div>
        </div>
    }
    <script type="text/javascript" src="assets/leaflet-src.js" charset="utf-8"></script>
    <script type="text/javascript" src="assets/easy-button.js" charset="utf-8"></script>

    @if (Model.HasExternalBaseLayer(ExternalBaseLayerType.BingMaps))
    {
    <script type="text/javascript" src="assets/leaflet-bing-layer.js" charset="utf-8"></script>
    }

    @if (!string.IsNullOrEmpty(Model.UTFGridUrl))
    {
        <script type="text/javascript" src="assets/L.UTFGrid-min.js" charset="utf-8"></script>
        @*
            <script type="text/javascript" src="assets/L.UTFGridCanvas.js" charset="utf-8"></script>
        *@
    }
    @if (Model.OverlayLayers != null)
    {
        foreach (var extLayer in Model.OverlayLayers)
        {
            if (extLayer.Type == OverlayLayerType.GeoJSON_FromMapGuide)
            {
                <script type="text/javascript" src="@(((GeoJSONFromMapGuideOverlayLayer)extLayer).Downloaded.ScriptRelPath)" charset="utf-8"></script>
            }
        }
    }
    <script type="text/javascript">

        var defaultStyle = {
            "clickable": true,
            "color": "#00D",
            "fillColor": "#00D",
            "weight": 1.0,
            "opacity": 0.3,
            "fillOpacity": 0.2
        };
        var defaultHoverStyle = {
            "fillOpacity": 0.5
        };

        var mapBounds = [
            [@Model.LatLngBounds[1], @Model.LatLngBounds[0]],
            [@Model.LatLngBounds[3], @Model.LatLngBounds[2]]
        ];
        var baseLayerList = [];
        var overlayList = [];
        @if (Model.ExternalBaseLayers != null)
        {
            int counter = 0;
            foreach (var extLayer in Model.ExternalBaseLayers)
            {
                switch (extLayer.Type)
                {
                    case ExternalBaseLayerType.OSM:
                        <text>
        var @(extLayer.Type)_@(counter) = L.tileLayer( '//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
            subdomains: ['a','b','c']
        });
        baseLayerList.push({ name: "@extLayer.Name", layer: @(extLayer.Type)_@(counter) });
                        </text>
                        break;
                    case ExternalBaseLayerType.Stamen:
                        <text>
        var @(extLayer.Type)_@(counter) = L.tileLayer( '//stamen-tiles-{s}.a.ssl.fastly.net/@(extLayer.LayerType.ToString().ToLower())/{z}/{x}/{y}.png', {
            attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.',
            subdomains: ['a','b','c']
        });
        baseLayerList.push({ name: "@extLayer.Name", layer: @(extLayer.Type)_@(counter) });
                        </text>
                        break;
                    case ExternalBaseLayerType.XYZ:
                        <text>
        var @(extLayer.Type)_@(counter) = L.tileLayer("@Raw(extLayer.UrlTemplate)");
        baseLayerList.push({ name: "@extLayer.Name", layer: @(extLayer.Type)_@(counter) });
                        </text>
                        break;
                    case ExternalBaseLayerType.BingMaps:
                        <text>
        var @(extLayer.Type)_@(counter) = L.tileLayer.bing({
            bingMapsKey: "@(((BingMapsBaseLayer)extLayer).ApiKey)",
            imagerySet: "@(((BingMapsBaseLayer)extLayer).LayerType)"
        });
        baseLayerList.push({ name: "@extLayer.Name", layer: @(extLayer.Type)_@(counter) });
                        </text>
                        break;
                }
                counter++;
            }
        }

        @if (!string.IsNullOrEmpty(Model.XYZImageUrl))
        {<text>
        var mainXYZImage = L.tileLayer("@Raw(Model.XYZImageUrl)", {
            attribution: 'Powered by MapGuide',
            maxZoom: 19,
            bounds: mapBounds
        });
        </text>
        }

        @if (!string.IsNullOrEmpty(Model.UTFGridUrl))
        {<text>
        var gUTFGridTipsEnabled = true;
        var gTrackingUTFGridTip = false;
        var mainUTFGrid = L.utfGrid("@Raw(Model.UTFGridUrl)", {
            fillColor: 'rgba(0, 0, 0, 0.5)',
            bounds: mapBounds
            //shadowBlur: 2,
            //shadowColor: 'black'
            // debug: false  // if true, show tile borders and tile keys
        });
        var infoElement = document.getElementById('feature-info');
        var nameElement = document.getElementById('feature-name');
        function setUTFGridTipsEnabled(bEnabled) {
            gUTFGridTipsEnabled = bEnabled;
            if (!gUTFGridTipsEnabled) {
                nameElement.innerHTML = "";
                infoElement.style.display = "none";
            }
        }
        mainUTFGrid.on('mouseover', function (e) {
            if (!gUTFGridTipsEnabled) {
                return;
            }
            //console.log("utfgrid mouseover");
            //console.log(e);
            if (e.data) {
                gTrackingUTFGridTip = true;
                /*
                var html = "<table>";
                for (var key in data) {
                    html += "<tr><td>" + key + "</td><td>" + data[key] + "</td></tr>";
                }
                html += "</table>";
                */
                var html = "";
                if (e.data.MG_TOOLTIP)
                    html += e.data.MG_TOOLTIP.replace(/(\\n)+/g, '<br />');
                if (e.data.MG_URL) {
                    html += "<br/><br/>";
                    html += "<strong>CTRL + Click for more information</strong>";
                }
                nameElement.innerHTML = html
                infoElement.style.display = null;
                //var cntPt = map.latLngToContainerPoint(e.latlng);
                //infoElement.style.left = (cntPt.x + 15) + "px";
                //infoElement.style.top = (cntPt.y + 15) + "px";
            }
            //infoOverlay.setPosition(data ? coordinate : undefined);
        });
        mainUTFGrid.on('mouseout', function (e) {
            if (!gUTFGridTipsEnabled) {
                return;
            }
            gTrackingUTFGridTip = false;
            //console.log("utfgrid mouseout");
            //console.log(e);
            //info.update();
            infoElement.style.display = "none";
        });
        </text>
        }

        @if (Model.OverlayLayers != null)
        {
            int counter = 0;
            foreach(var extLayer in Model.OverlayLayers)
            {
                switch (extLayer.Type)
                {
                    case OverlayLayerType.GeoJSON_FromMapGuide:
                        <text>
        var @(extLayer.Type)_@(counter) = L.geoJSON(@(((GeoJSONFromMapGuideOverlayLayer)extLayer).Downloaded.GlobalVar), {
            style: @(((GeoJSONFromMapGuideOverlayLayer)extLayer).Downloaded.GlobalVar)_style || defaultStyle,
            pointToLayer: @(((GeoJSONFromMapGuideOverlayLayer)extLayer).Downloaded.GlobalVar)_style_point,
            onEachFeature: @(((GeoJSONFromMapGuideOverlayLayer)extLayer).Downloaded.GlobalVar)_popup_template
        });
        overlayList.push({ name: "@(extLayer.Name)", visible: @(extLayer.InitiallyVisible ? "true" : "false"), layer: @(extLayer.Type)_@(counter) });
                        </text>
                        break;
                    case OverlayLayerType.WMS:
                        <text>
        var @(extLayer.Type)_@(counter) = L.tileLayer.wms("@Raw(((WMSOverlayLayer)extLayer).Service)", {
            layers: "@(((WMSOverlayLayer)extLayer).Layer)",
            format: "image/png",
            transparent: true,
            uppercase: true
        });
        overlayList.push({ name: "@(extLayer.Name)", visible: @(extLayer.InitiallyVisible ? "true" : "false"), layer: @(extLayer.Type)_@(counter) });
                        </text>
                        break;
                    default:
                        <text>
        console.warn("Overlay layer type (@extLayer.Type) not yet supported");
                        </text>
                        break;
                }
                counter++;
            }
        }

        var mainLayers = L.layerGroup([mainXYZImage, mainUTFGrid]);
        var base = {};
        var overlays = {};

        for (var i = 0; i < baseLayerList.length; i++) {
            var bn = baseLayerList[i];
            base[bn.name] = bn.layer;
        }

        overlays["Main Map"] = mainLayers;

        for (var i = 0; i < overlayList.length; i++) {
            var bn = overlayList[i];
            overlays[bn.name] = bn.layer;
        }

        var initLayers = [];
        if (baseLayerList.length > 0) {
            initLayers.push(baseLayerList[0].layer);
        }
        initLayers.push(mainLayers);
        var map = L.map('map', {
            layers: initLayers
        }).fitBounds(mapBounds);
        L.control.layers(base, overlays).addTo(map);

        @if (!string.IsNullOrEmpty(Model.UTFGridUrl))
        {<text>

        var utfGridTipToggleBtn = L.easyButton({
            states: [
                {
                    stateName: 'enable-tile-tooltips',      // name the state
                    icon:      'icon-comment',              // and define its properties
                    title:     'Enable tile tooltips',      // like its title
                    onClick: function (btn, map) {          // and its callback
                        setUTFGridTipsEnabled(false);
                        btn.state('disable-tile-tooltips'); // change state on click!
                    }
                },
                {
                    stateName: 'disable-tile-tooltips',
                    icon:      'icon-comment',
                    title:     'Disable tile tooltips',
                    onClick: function (btn, map) {
                        setUTFGridTipsEnabled(true);
                        btn.state('enable-tile-tooltips');
                    }
                }
            ]
        });

        utfGridTipToggleBtn.addTo( map );

        map.on("mousemove", function (e) {
            if (gTrackingUTFGridTip) {
                var cntPt = e.containerPoint;
                infoElement.style.left = (cntPt.x + 15) + "px";
                infoElement.style.top = (cntPt.y + 15) + "px";
            }
        });
        </text>
        }
    </script>
</body>

</html>